package com.ilioili.proabslist;

import android.view.View;
import android.widget.AbsListView;
import android.widget.Adapter;

public class ListViewStateUtil {

    /**
     * @return 是否已经滑动到顶部
     */
    public static boolean isToTop(AbsListView listView) {
        return isFirstItemTotallyVisible(listView);
    }

    /**
     * 判断第一个child是否完全显示出来
     *
     * @return true完全显示出来，否则false
     */
    private static boolean isFirstItemTotallyVisible(AbsListView listView) {
        Adapter adapter = listView.getAdapter();
        if (null == adapter || adapter.isEmpty()) {
            return true;
        }
        if (listView.getFirstVisiblePosition() != 0) {
            return false;
        }
        if (listView.getChildCount() == 0) {
            return true;
        }
        int firstTop = listView.getChildAt(0).getTop();
        if (firstTop >= 0) {
            return true;
        }
        return false;
    }

    /**
     * @return 是否已经滑动到底部
     */
    public static boolean isToBottom(AbsListView listView) {
        return isLastItemTotallyVisible(listView);
    }


    //    final int childCount = getChildCount();
    //    if (childCount == 0) {
    //        return false;
    //    }
    //
    //    final int firstPosition = mFirstPosition;
    //    final Rect listPadding = mListPadding;
    //    if (direction > 0) {
    //        final int lastBottom = getChildAt(childCount - 1).getBottom();
    //        final int lastPosition = firstPosition + childCount;
    //        return lastPosition < mItemCount || lastBottom > getHeight() - listPadding.bottom;
    //    } else {
    //        final int firstTop = getChildAt(0).getTop();
    //        return firstPosition > 0 || firstTop < listPadding.top;
    //    }

    /**
     * 判断最后一个child是否完全显示出来
     *
     * @return true完全显示出来，否则false
     */
    private static boolean isLastItemTotallyVisible(AbsListView listView) {
        final Adapter adapter = listView.getAdapter();
        if (null == adapter || adapter.isEmpty()) {
            return true;
        }

        final int lastItemPosition = adapter.getCount() - 1;
        final int lastVisiblePosition = listView.getLastVisiblePosition();

        if (lastVisiblePosition >= lastItemPosition - 1) {
            final int childIndex = lastVisiblePosition - listView.getFirstVisiblePosition();
            final int childCount = listView.getChildCount();
            final int index = Math.min(childIndex, childCount - 1);
            final View lastVisibleChild = listView.getChildAt(index);
            if (lastVisibleChild != null) {
                return lastVisibleChild.getBottom() <= listView.getBottom();
            }
        }

        return false;
    }


}
